package com.medical.standard.util;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

public class WordExportUtil {

    /**
     * 导出产品技术要求为HTML格式（Word可打开）
     */
    public static void exportProductRequirementDoc(HttpServletResponse response,
                                                   Map<String, Object> requirementData) throws IOException {

        response.setContentType("application/msword");
        response.setCharacterEncoding("UTF-8");
        String encodedFileName = new String("产品技术要求.doc".getBytes("UTF-8"), "ISO-8859-1");
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);

        try (PrintWriter writer = response.getWriter()) {
            // 生成HTML格式的Word文档
            StringBuilder html = new StringBuilder();

            html.append("<html xmlns:o='urn:schemas-microsoft-com:office:office' ")
                    .append("xmlns:w='urn:schemas-microsoft-com:office:word' ")
                    .append("xmlns='http://www.w3.org/TR/REC-html40'>")
                    .append("<head>")
                    .append("<meta charset='UTF-8'>")
                    .append("<title>医疗器械产品技术要求</title>")
                    .append("<style>")
                    .append("body { font-family: 宋体; margin: 2cm; }")
                    .append(".title { text-align: center; font-size: 18pt; font-weight: bold; margin-bottom: 1cm; }")
                    .append(".section-title { font-size: 14pt; font-weight: bold; margin-top: 0.5cm; margin-bottom: 0.3cm; }")
                    .append(".content { font-size: 12pt; line-height: 1.5; text-indent: 2em; margin-bottom: 0.3cm; }")
                    .append(".page-break { page-break-before: always; }")
                    .append("</style>")
                    .append("</head>")
                    .append("<body>");

            // 标题
            html.append("<div class='title'>医疗器械产品技术要求</div>");

            // 产品型号/规格及其划分说明
            html.append("<div class='section-title'>1. 产品型号/规格及其划分说明</div>");
            html.append("<div class='content'>")
                    .append(escapeHtml(getValue(requirementData, "productModel", "暂无内容")))
                    .append("</div>");

            // 性能指标
            html.append("<div class='section-title'>2. 性能指标</div>");
            html.append("<div class='content'>")
                    .append(escapeHtml(getValue(requirementData, "performance", "暂无内容")))
                    .append("</div>");

            // 检验方法
            html.append("<div class='section-title'>3. 检验方法</div>");
            String inspectionMethod = getValue(requirementData, "inspectionMethod", "暂无内容");
            // 处理检验方法中的固定句式
            if (inspectionMethod.contains("_")) {
                inspectionMethod = inspectionMethod.replace("_", "实验结果应符合______的要求");
            }
            html.append("<div class='content'>")
                    .append(escapeHtml(inspectionMethod))
                    .append("</div>");

            // 术语
            html.append("<div class='section-title'>4. 术语</div>");
            html.append("<div class='content'>")
                    .append(escapeHtml(getValue(requirementData, "terminology", "暂无内容")))
                    .append("</div>");

            // 附录（分页）
            String appendix = getValue(requirementData, "appendix", "");
            if (!appendix.trim().isEmpty()) {
                html.append("<div class='page-break'></div>")
                        .append("<div class='title'>附录</div>")
                        .append("<div class='content'>")
                        .append(escapeHtml(appendix))
                        .append("</div>");
            }

            html.append("</body></html>");

            writer.write(html.toString());
            writer.flush();
        }
    }

    /**
     * HTML转义
     */
    private static String escapeHtml(String text) {
        if (text == null) return "";
        return text.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#39;")
                .replace("\n", "<br>");
    }

    /**
     * 从数据中获取值
     */
    private static String getValue(Map<String, Object> data, String key, String defaultValue) {
        if (data == null) return defaultValue;
        Object value = data.get(key);
        return value != null ? value.toString() : defaultValue;
    }

    /**
     * 创建简单的表格格式检验方法
     */
    public static void exportInspectionMethodTable(HttpServletResponse response,
                                                   String[][] tableData,
                                                   String[] headers) throws IOException {

        response.setContentType("application/msword");
        response.setCharacterEncoding("UTF-8");
        String encodedFileName = new String("检验方法表.doc".getBytes("UTF-8"), "ISO-8859-1");
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);

        try (PrintWriter writer = response.getWriter()) {
            StringBuilder html = new StringBuilder();

            html.append("<html><head><meta charset='UTF-8'><title>检验方法表</title>")
                    .append("<style>")
                    .append("body { font-family: 宋体; margin: 2cm; }")
                    .append("table { border-collapse: collapse; width: 100%; margin-top: 0.5cm; }")
                    .append("th, td { border: 1px solid black; padding: 8px; text-align: left; }")
                    .append("th { background-color: #f2f2f2; font-weight: bold; }")
                    .append("</style></head><body>")
                    .append("<h2 style='text-align: center;'>检验方法表</h2>")
                    .append("<table>")
                    .append("<tr>");

            // 表头
            for (String header : headers) {
                html.append("<th>").append(escapeHtml(header)).append("</th>");
            }
            html.append("</tr>");

            // 数据行
            if (tableData != null) {
                for (String[] row : tableData) {
                    html.append("<tr>");
                    for (String cell : row) {
                        html.append("<td>").append(escapeHtml(cell != null ? cell : "")).append("</td>");
                    }
                    html.append("</tr>");
                }
            }

            html.append("</table></body></html>");

            writer.write(html.toString());
            writer.flush();
        }
    }
}